package com.pig4cloud.pig.module.controller.agent;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pig.admin.api.dto.UserDTO;
import com.pig4cloud.pig.admin.api.dto.UserInfo;
import com.pig4cloud.pig.admin.api.entity.SysUser;
import com.pig4cloud.pig.admin.api.feign.RemoteUserService;
import com.pig4cloud.pig.common.core.constant.SecurityConstants;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.mybatis.page.PageUtils;
import com.pig4cloud.pig.common.mybatis.page.TableDataInfo;
import com.pig4cloud.pig.common.security.service.PigUser;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import com.pig4cloud.pig.module.api.entity.agent.AgentCompany;
import com.pig4cloud.pig.module.api.entity.agent.AgentUser;
import com.pig4cloud.pig.module.api.entity.wx.WxUser;
import com.pig4cloud.pig.module.service.agent.IAgentCompanyService;
import com.pig4cloud.pig.module.service.agent.IAgentUserService;
import com.pig4cloud.pig.module.service.wx.IWxUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.List;

/**
 * 代理绑定管理用户Controller
 *
 * @author ruoyi
 * @date 2022-12-14
 */
@Validated
@Api(value = "代理绑定管理用户控制器", tags = {"代理绑定管理用户管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/agentUser")
public class AgentUserController {

    private final IAgentUserService agentUserService;
    private final IWxUserService wxUserService;
    private final IAgentCompanyService agentCompanyService;
    private final RemoteUserService remoteUserService;
	@Value("${ruoyi.imgUrl}")
	private String imgUrl;

    /**
     * 查询代理绑定管理用户列表
     */
    @ApiOperation("查询代理绑定管理用户列表")
    @PreAuthorize("@pms.hasPermission('module:agentUser:list')")
    @GetMapping("/list")
    public TableDataInfo<AgentUser> list(@Validated AgentUser agentUser) {
        QueryWrapper<AgentUser> qw = new QueryWrapper<>();
		if (agentUser.getAgentId()!=null){
			qw.eq("agent_id",agentUser.getAgentId());
		}
        TableDataInfo<AgentUser> td = PageUtils.buildDataInfo(agentUserService.page(PageUtils.buildPage(),qw));
        List<AgentUser> list = td.getData();
        for (AgentUser list1:list){
            if (ObjectUtil.isNotEmpty(list1.getAgentId())){
                AgentCompany company = agentCompanyService.findById(list1.getAgentId());
                if (company != null){
                    list1.setAgentName(company.getAgentName());
                }
            }
            if (ObjectUtil.isNotEmpty(list1.getSysUserId())){
				R<UserInfo> userInfo = remoteUserService.userDetail(list1.getSysUserId(), SecurityConstants.FROM_IN);
                SysUser sysUser = userInfo.getData().getSysUser();
                if (sysUser != null){
                    list1.setSysUserName(sysUser.getName());
                }
            }
            if (ObjectUtil.isNotEmpty(list1.getUserId())){
                WxUser user = wxUserService.findById(list1.getUserId());
                if (user != null){
					if(StrUtil.isNotEmpty(user.getFaceUrl()) && !user.getFaceUrl().contains("http")) {
						list1.setFaceUrl(imgUrl + user.getFaceUrl());
					}else{
						list1.setFaceUrl(user.getFaceUrl());
					}
                    list1.setNickName(user.getNickName());
                }
            }
        }
        return td;
    }

    /**
     * 导出代理绑定管理用户列表
     */
    @ApiOperation("导出代理绑定管理用户列表")
    @PreAuthorize("@pms.hasPermission('module:agentUser:export')")
    @SysLog("代理绑定管理用户")
    @GetMapping("/export")
    public List export(@Validated AgentUser agentUser) {
        List<AgentUser> list = agentUserService.list();
        // ExcelUtil<AgentUser> util = new // ExcelUtil<AgentUser>(AgentUser.class);
        return  list;// util.exportExcel(list, "代理绑定管理用户");
    }

    /**
     * 获取代理绑定管理用户详细信息
     */
    @ApiOperation("获取代理绑定管理用户详细信息")
    @PreAuthorize("@pms.hasPermission('module:agentUser:query')")
    @GetMapping("/{id}")
    public R<AgentUser> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        AgentUser agentUser = agentUserService.getById(id);
        return R.ok(agentUser);
    }

    /**
     * 新增代理绑定管理用户
     */
    @ApiOperation("新增代理绑定管理用户")
    @PreAuthorize("@pms.hasPermission('module:agentUser:add')")
    @SysLog("代理绑定管理用户")

    @PostMapping()
    public R<Void> add(@Valid @RequestBody AgentUser agentUser) {
		PigUser pigUser = SecurityUtils.getUser();
		UserDTO sysUser = new UserDTO();
		sysUser.setUsername(agentUser.getUserName());
		sysUser.setPassword("123456");
        sysUser.setCreateBy(pigUser.getUsername());
//        sysUser.setRoleId(109);
        sysUser.setUserType(1);
//        sysUser.setStatus("0");
		R<Long> ret = remoteUserService.addUser(sysUser, SecurityConstants.FROM_IN);
		if(ret.getCode() == 0){
			agentUser.setSysUserId(ret.getData());
			return R.okByRow(agentUserService.save(agentUser) ? 1 : 0);
		}
		return R.failed();
    }

    /**
     * 修改代理绑定管理用户
     */
    @ApiOperation("修改代理绑定管理用户")
    @PreAuthorize("@pms.hasPermission('module:agentUser:edit')")
    @SysLog("代理绑定管理用户")

    @PutMapping()
    public R<Void> edit(@Valid @RequestBody AgentUser agentUser) {
        return R.okByRow(agentUserService.updateById(agentUser) ? 1 : 0);
    }

    /**
     * 删除代理绑定管理用户
     */
    @ApiOperation("删除代理绑定管理用户")
    @PreAuthorize("@pms.hasPermission('module:agentUser:remove')")
    @SysLog("代理绑定管理用户")
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
        return R.okByRow(agentUserService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
